[#ftl]
[#include "_WorkspaceContext.ftl"/]
[@extend "dojo/dnd/Source"]
 	prototype:false[#--custom property--]
 	,onDndDrop:function(source, nodes, copy, target,event){
 		if(this==target){
 			if(!this.prototype){
 				this.onDrop(source, nodes, copy);
 			}else{
 				this.f(nodes[0],event);
 			}
 		}
 		this.onDndCancel();
	}
 	,f:function(iconNode,event){
 		var template = "";
		query(".template",iconNode).forEach(function(node){
			template = node.value;
		});
		var widgetClass = ""
		query(".widgetClass",iconNode).forEach(function(node){
			widgetClass = node.value;
		});
		var warpper = "";
		query(".warpper",iconNode).forEach(function(node){
			warpper = node.value;
		});
//		console.log("widgetClass=",widgetClass,"template=",template,"warpper=",warpper,"force=",[#if applicationMode = "DEV"]true[#else]false[/#if]);
		if(agile.requireX(widgetClass,[#if applicationMode = "DEV"]true[#else]false[/#if])){
			if(warpper){
				agile.requireX(warpper,[#if applicationMode = "DEV"]true[#else]false[/#if]);
			}					
			this.createComponent(widgetClass,template,event);
		}		
 	}
 	[@method "createComponent"/]
	,createComponent:function(widgetClass,template,event){
//		console.warn("#############widgetClass=",widgetClass,"template=",template,"event.target=",event.target);
		var enclosingWidget = registry.getEnclosingWidget(event.target);
		if(!enclosingWidget.get("readOnly")){
			var offset = this.getOffset(event);
			var widget = this._createWidget(widgetClass,template,event); 
//			console.warn("#############created widget=",widget)
			enclosingWidget.addComponent(widget,offset);
			widget.computeSize();
			topic.publish("agile.widget.selected",widget);	
			widget.onSelected();
			agile.commit([{action:"add",target:widget}]);
		}else{
			topic.publish("agile.message","error",null,"i18n_can_not_edit_widget");
		}
	}
 	,_createWidget:function(widgetClass,template,event){
		
		var widget = null;
		try{			
			if(widgetClass == "agile.TemplateWidget" && window.ls[template]){			
				var div = construct.create("div",{innerHTML:window.ls[template]});
				parser.parse(div);			
				widget = registry.getEnclosingWidget(div.firstChild);	
			}else{			
				var mockupRef = "w"+ (new Date().getTime());	
				eval(lang.replace("kernel.global.{mockupRef} = new {template}",{mockupRef:mockupRef,template:template}));
				widget = kernel.global[mockupRef];				
			}
			
			if(widgetClass == "agile.TemplateWidget"){
				widget.set("master",true);	
				widget.resetWid();				
			}
		}catch(e){
			console.error("Error occurred while creating widget:" + widgetClass,e);
			topic.publish("agile.message.error",null,agile.i18n("can_not_create_widget",null,"Can not create widget"));			
		}
		
		return widget;
 	}
	,getOffset:function(event){
//		//console.log("event.offsetX",event.offsetX);
		if(event.offsetX == undefined){
			var containerBox = agile.coords(event.target,true);
			event.offsetX = event.clientX - containerBox.x;
			event.offsetY = event.clientY - containerBox.y;
		}
		return {left:event.offsetX,top:event.offsetY};
	}
 [/@]


[@define "agile.MockupEditPage" 
 "ContentPane,_TemplatedMixin,_WidgetsInTemplateMixin,agile._Container,agile._WorkspaceContext,agile._MetadataMixin"
 "DndSource=dojo/dnd/Source,HorizontalRule=dijit/form/HorizontalRule,HorizontalRuleLabels=dijit/form/HorizontalRuleLabels,VerticalRule=dijit/form/VerticalRule,VerticalRuleLabels=dijit/form/VerticalRuleLabels"]
	parseOnLoad:false	
	,selectedTarget:null	
	,hasSelector:true
	,closable:true
	[#assign dndSourceId]dndSource${.now?string("yyyyMMddHHmmSS")}[/#assign]
	[#assign templateString]
	<div style="overflow:hidden;margin:0px;padding:0px;border:0px solid;width:100%;height:97%;">
		<div data-dojo-attach-point='ruleContainerNode' style="margin-left:10px;width:100%;height:100%;z-index:-100;"></div>
		<div data-dojo-attach-point="containerNode" class="agileCanvas"></div>
	</div>	
	[/#assign]
	,templateString:"${templateString?js_string}"	
    ,templateMap:{
		dojo:'<div style="display:none" class="metadata">&#123;{style-props}&#125;</div>{innerWidets}'
		,agile:'<div style="display:none" class="metadata">&#123;{style-props}&#125;</div>{innerWidets}'	
	}

	,styleConstraints:agile.delegate(agile._MetadataMixin.prototype.styleConstraints,{
		"left": {_ignore:true}
		,"top": {_ignore:true}
		,"z-index": {_ignore:true}
		,"height":{_ignore:true}
		,"width":{_ignore:true
//			   readOnly:function(widget){
//		   		   return true;	   			
//		   	   }
//			   ,onValueChange:function(ownerWidget,name,htmlName,value){
//					style.set(ownerWidget.getStyleNodes()[0],name,value);					
//			   }
		   	}
	})
	,events:agile.delegate(agile._MetadataMixin.prototype.events,{
		
	})
	,attributes:agile.delegate(agile._MetadataMixin.prototype.attributes,{
		title:lang.mixin({},agile.TextMetadata,{
			label:agile.i18n("title",null,true),name:"title",pattern:"[^{};,]*"
			,onValueChange:function(/*widget*/widget,/*String*/name,/*Object*/value){		
//				console.log("@@@@@@@@",name,value);
				widget.workspace.adviseTitle(widget,value);
			}
		})
		,comment: lang.mixin({},agile.MultiTextMetadata ,{label:agile.i18n("comment",null,true),name:"comment"})
	})
	,constructor:function(params,node){	
//		console.log(this.declaredClass,"##########params=",params);
		
		this.metadata("parameters",params);
		this.metadata("anchor",{left:0,top:0});
		this.metadata("dojoDeclaredClass","");
		
		//false if the store is specified to load store data
		this.fetched = !params.store;
		if(!params.store){
			this.metadata("parameters.store",new Date().getTime());
		}
		if(!params.title){
			var title = "page"+ (new Date().getTime());
			this.metadata("parameters.title",title);
			this.set("title",title);
		}
		
		
//		this.subscribe("agile.ready",function(obj){
//			if(obj == "Application"){
//				this._applicationReady = true;
//				this.resize();
//			}
//		});
//		
//		//only resize after application is ready
		aspect.after(this,"resize",lang.hitch(this,function(){
//			if(this._applicationReady){
//			console.log("Page-resize ###",this.title);
				this.resetCanvas();
//			}
		}));	
//		
//		aspect.after(this,"startup",lang.hitch(this,"resetCanvas"));
		//only execute once to calculate children size
//		on(this,"resize",this,function(){	
//			
//			console.log("Page-resize-child@@@@@@@@@",this._childrenResized);
//			
//			if(this._childrenResized){return;}
//			this._childrenResized = true;
//			
//			//var box = agile.calcSize(this.containerNode);
//			this.metadata("anchor",{left:0,top:0});
//
//			array.forEach(this._getChildren(),function(child){
//				console.log("Page-resize-child=",child);
//				child.metadata("anchor",this.metadata("anchor"));			
//				child.computeSize();
//			},this);			
//		});	
			
		this.subscribe("agile.page.selected",function(page){
			if(!page && this.isSelected()){
//				console.error(this.declaredClass,"agile.page.selected")
				topic.publish("agile.widget.selected",this);
				this.editable = this.metadata("parameters.editable");				
				if(this.titleWidget)this.titleWidget.set("disabled",!this.editable);
			}
		});			
	
//		this.subscribe("agile.ready",function(obj){
//			if(obj == "Application" && this.isSelected()){
//				topic.publish("agile.widget.selected",this);
//			}
//		});
		
		this.watch("title",lang.hitch(this,function(name,old,value){
			this.metadata("parameters.title",value);
			topic.publish("agile.page.changed",{id:this.id,title:value});
		}));
		
//		aspect.after(this,"startup",lang.hitch(this,function(){
////			if(this.controlButton){
////				on(this.controlButton.closeNode,"click",function(){
//					
//					console.log(this.title," is closed@@",this)
//					console.log(this.title," is closed##",this.controlButton)
////				});
////			}
//		}));
	}	
	,isSelected:function(){
		return this.selected;
	}
    ,postCreate:function(){	
    	//this.store = this.title;    	
    	try{
	    	if(/*this.store == null && */string.trim(this.containerNode.innerHTML) != ""){
	    		agile.requireClazz(this.containerNode);
	    	}
	    	
	    	var dndSource = new DndSource(this.containerNode,{isSource:false, prototype:true});
	    	dndSource.startup();
	    	//20141022:
	    	this.subscribe("create-widget",function(selectedIcon,event){
	    		if(this.selected){
	    			dndSource.f(selectedIcon,event);
	    		}
	    	});
	    	
    	}catch(e){
    		topic.publish("agile.message","error",null,"Error occurred while initializing page",e);
    	}
      	
    	this._size = this.getCanvasSize();
    	
//    	style.set(this.getContainerNode(),"overflow","auto");
    	
	}
	,getCanvasSize:function(){
		var box = agile.calcSize(this.domNode);
		var width = Math.floor(box.w) - 10;
		var height = Math.floor(box.h) - 15;
		return {w:width,h:height};
	}
	,resetCanvas:function(){
		var size = this.getCanvasSize();
		
		if(size["w"] == this._size["w"] && size["h"] == this._size["h"]){
			return;
		} 
		this._size = size;
//		console.log("resetCanvas:",this.title)
		//console.log(this.declaredClass,"this.templateString=",this.templateString,"this.containerNode:",this.containerNode,"this.ruleContainerNode=",this.ruleContainerNode);
//			style.set(this.containerNode,{width:this.metadata("style.width") +"px",height:this.metadata("style.height") +"px"});
		style.set(this.containerNode,{width:this._size["w"] +"px",height:this._size["h"] +"px"});
		this.initCanvasRules();		
//		console.log("@@@@@@@@@@@@@@@@@@@@@@@@")
		this.metadata("style.width",this._size["w"] +"px");
		this.metadata("style.height",this._size["h"] +"px");
	}
	,initCanvasRules:function(){
//		console.log("initCanvasRules:",this.title)
		query(".temp",this.ruleContainerNode).forEach(function(node){
			  construct.destroy(node);
//			regristry.byNode(node).destroyRecursive();
		});
		
		var width = this._size["w"];
		var height = this._size["h"]
//		console.log("width",width,"height",height);
		//var marginBox = agile.calcSize(this.domNode);		
					
		var vRuleLables = [];
		for(var i = Math.floor(height/100); i > 0; i--){
			vRuleLables[vRuleLables.length] = i * 100;
		}
		vRuleLables[vRuleLables.length] = '';
//		//console.log("vRuleLables",vRuleLables);
		
		var vrulesNode = document.createElement('div');        			
		var verticalRuleCount = Math.round(height/10);
		var verticalRule = new VerticalRule({count:verticalRuleCount,style:"width:2px;margin-left:-10px"},vrulesNode);		
		construct.place(verticalRule.domNode,this.ruleContainerNode,"first");
		domClass.add(verticalRule.domNode,"temp");
		verticalRule.startup();
					
		var vruleLabelNode = document.createElement('div');
		var vRuleLables = new VerticalRuleLabels({labels:vRuleLables, style:"width:5px;font-size:100%;color:gray;"},vruleLabelNode);						
		construct.place(vRuleLables.domNode,this.ruleContainerNode,"first");
		domClass.add(vRuleLables.domNode,"temp");
		style.set(vRuleLables.domNode,{height:(Math.floor(height/100) * 100) +"px",zIndex:100});
		vRuleLables.startup();
		
	    var rulesNode = document.createElement('div');        			
		var horizontalRuleCount = Math.round(width/10);
		var horizontalRule = new HorizontalRule({count:horizontalRuleCount,style:"height:2px;"},rulesNode);
		construct.place(horizontalRule.domNode,this.ruleContainerNode,"first");
		domClass.add(horizontalRule.domNode,"temp");
		horizontalRule.startup();		
		
		var hRuleLables = [];
		for(var i = 0, count= Math.floor(width/100); i <= count; i++){
			hRuleLables[hRuleLables.length] = i * 100;
		}
//		//console.log("hRuleLables",hRuleLables);
		
		var ruleLabelNode = document.createElement('div');
		var horizontalRuleLables = new HorizontalRuleLabels({labels:hRuleLables, style:"height:10px;font-size:100%;color:gray;"},ruleLabelNode);						
		construct.place(horizontalRuleLables.domNode,this.ruleContainerNode,"first");
		domClass.add(horizontalRuleLables.domNode,"temp");
		style.set(horizontalRuleLables.domNode,"width",(Math.floor(width/100) * 100) +"px");
		horizontalRuleLables.startup();	
	}
	,initTitleEditor:function(){
		if(!this.editable){
			return;
		}
//		console.log("controlButton=",this.controlButton.containerNode);
//		if(!this.titleWidget){
//			this.titleWidget = new InlineEditBox({width:"100px"},this.getTitleTextNode());		
//			this.titleWidget.startup();
//			agile.stopInlineEditBox(this.titleWidget);
//		}
//		
//		if(this.metadata("parameters.title")){
//			 this.titleWidget.set("value",this.metadata("parameters.title"));
//		}
	}
	,getTitleTextNode:function(){
		return this.controlButton.containerNode;
	}		
	,getFocusNode:function(){
		return this.controlButton.focusNode;
	}
	,getToolbarAnchorNode:function(){	
		return this.controlButton.focusNode;			
	}
	
	,onSelected:function(){
		//nothing to do
//		topic.publish("agile.widget.selected",this);
	}
	,onDeselected:function(){
		//nothing to do
	}
	,beforeDataReady:function(){
		query(".metadata",this.containerNode).forEach(function(node){
			construct.destroy(node);			
		},this);
//		console.log("1@@@@@@@@@@@@",this.metadata("parameters.style"));
	}
	,onDataReady:function(){
//		console.log("@@@@@@@@@@@@onDataReady..1");
		this.inherited(arguments);
//		console.log("@@@@@@@@@@@@onDataReady..1.1");
		query(".metadata",this.containerNode).forEach(function(node){
//			console.log(this.title,"@@@@@@@@@@@@onDataReady@@@",node.innerText,node);
			if(node.innerText){
//				lang.mixin(this.metadata("parameters"),json.parse(node.innerText,false));
				var params = json.parse(node.innerText,false);
				this.mixinMetadata(params);
			}
		},this);
		this.editable = this.metadata("parameters.editable");
//		console.log("@@@@@@@@@@@@onDataReady..2");
//		this.mixInMetadata();

		this._applyParameterStyle = false;
		this.applyParameterStyle();

//		console.log("@@@@@@@@@@@@onDataReady..3");
		//calculate the initial size 
		this.metadata("anchor",{left:0,top:0});
		array.forEach(this._getChildren(),function(child){
//			console.log("Page-resize-child=",child);
			child.metadata("anchor",this.metadata("anchor"));			
			child.computeSize();
		},this);
//		console.log("@@@@@@@@@@@@onDataReady...metadata=",this.metadata());	
		
		this.initTitleEditor();		
		
	}
	,getStyleNodes:function(){
		return [this.containerNode];
	}
	//advise the state for the context menu
	,adviseContextState:function(param){
		return param == "Preview" || param == "Refresh" || (param == "Save" && this.editable);		
	}
	,toHtml:function(params){
		//TODO:tentative solution
		//console.log("#########################",this.metadata("style"))
		return this.inherited(arguments).replace("&#123;","{").replace("&#125;","}");
	}
	,onClose:function(parent, page){		
		parent.removeChild(page);
		//return false to not destroy the page in case of close
		topic.publish("agile.page.changed",{id:page.id,open:false});
		return false;
	}
	,onShow:function(){
		this.shortName = this.get("title");
//		console.log("On show", this.title)
		//fetch content for the first time
		if(!this.fetched){			
			this.refresh(true);
		}	
		topic.publish("agile.widget.selected",this);		
	}
	
	,refresh:function(force){		
		if(this.store){
			if(force){				
				this.set("content",lang.replace("<div style='position:absolute;left:45%;top:30%;color:#0000ff;font-size:2em'>{loadingMessage}</div>",{loadingMessage:agile.i18n("loadingMsg",null,"Loading...Please wait")}));
				//delay the		
				window.setTimeout(lang.hitch(this,function(){
					agile.load(this.store,this,this.onDownloadEnd);	
				}),50);
			}else{
				topic.publish("agile.message.confirm","i18n_confirm_refresh",null,this,{
					ok:function(){						
						agile.load(this.store,this,this.onDownloadEnd);							
					},
					cancel:function(){						
					}
				});	
			}
		}
	}
[/@]
